package com.tqjc.system.core.socket;

import com.alibaba.fastjson.JSON;
import com.tqjc.system.common.constant.GlobalConstant;
import com.tqjc.system.core.config.WebSocketConfigurator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 86195
 * @version 1.0
 * @description 刷新车辆websocket服务类
 * @date 2023/9/22 15:41
 */
@ServerEndpoint(value = "/refreshCarInfo",configurator = WebSocketConfigurator.class)
@Component("CarIndexInfoWebSocketService")
@Slf4j
public class CarInfoWebsocketService  {

    private static Map<String, Session> sessionMap = new HashMap<>();


    @OnOpen
    public void onOpen(Session session){
        log.info("CarInfoWebsocketService start");
        String ip = (String) session.getUserProperties().get(GlobalConstant.STRING_IP);
        //将session储存进来
        sessionMap.put(ip,session);
    }


    @OnMessage
    public void onMessage(String message){
        //todo 查询数据库信息发送至前端
        Map map = new HashMap(2);
        map.put("data",message);
        for (Map.Entry<String, Session> entry : sessionMap.entrySet()) {
            try {
                entry.getValue().getBasicRemote().sendText(JSON.toJSONString(map));
            } catch (Exception e){
                log.error("ip:{}发送道闸更新数据异常",entry.getKey());
            }
        }
    }

    @OnClose
    public void onClose(Session session){
        //断开连接，删除session
        String ip = (String) session.getUserProperties().get(GlobalConstant.STRING_IP);
        sessionMap.remove(ip);

    }



}
